package com.meiyu.live.tv.anchor;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.netease.LSMediaCapture.lsMediaCapture;
import com.netease.LSMediaCapture.lsMediaCapture.LSLiveStreamingParaCtx;
import com.netease.LSMediaCapture.lsMediaCapture.Statistics;
import com.netease.LSMediaCapture.lsMessageHandler;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.chatroom.ChatRoomMessageBuilder;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.ChatRoomServiceObserver;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomResultData;
import com.umeng.socialize.UMShareAPI;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.BaseApplication;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.DealEvent;
import com.meiyu.live.eventbus.NowLiveUpdateEvent;
import com.meiyu.live.eventbus.RechargeEvent;
import com.meiyu.live.eventbus.WinEvent;
import com.meiyu.live.eventbus.YazhuEvent;
import com.meiyu.live.net.FileReqPackage;
import com.meiyu.live.net.UploadFile;
import com.meiyu.live.net.callback.UploadCallBack;
import com.meiyu.live.net.param.AddnumParams;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.GetrobotsParam;
import com.meiyu.live.net.param.GointoGameParams;
import com.meiyu.live.net.param.PostbarrageParams;
import com.meiyu.live.net.param.UploadFileParams;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.net.response.CoinsResponse;
import com.meiyu.live.net.response.CreateRooomResponse;
import com.meiyu.live.net.response.DealResponse;
import com.meiyu.live.net.response.LiveGiftResponse;
import com.meiyu.live.net.response.UploadResponse;
import com.meiyu.live.popj.Gift;
import com.meiyu.live.popj.GiftForLive;
import com.meiyu.live.popj.PersonalInfo;
import com.meiyu.live.popj.RelationInfo;
import com.meiyu.live.popj.RoomDanmuMessage;
import com.meiyu.live.popj.RoomMessage;
import com.meiyu.live.tv.utils.ChatRoomMessageParser;
import com.meiyu.live.tv.widget.AtmosphereView;
import com.meiyu.live.tv.widget.BeautySettingView;
import com.meiyu.live.tv.widget.DanmuShowView;
import com.meiyu.live.tv.widget.GameListView;
import com.meiyu.live.tv.widget.GiftGifShowView;
import com.meiyu.live.tv.widget.GiftSendView;
import com.meiyu.live.tv.widget.GiftShowView;
import com.meiyu.live.tv.widget.InputView;
import com.meiyu.live.tv.widget.PrivateMessageView;
import com.meiyu.live.tv.widget.RoomManageListPopwindow;
import com.meiyu.live.tv.widget.RoomMessageAdapter;
import com.meiyu.live.tv.widget.ToolsView;
import com.meiyu.live.tv.widget.TvTitleView;
import com.meiyu.live.util.DisplayUtils;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.GamePopupwind;
import com.meiyu.live.widget.RoomManageDialog;
import com.meiyu.live.widget.ShareDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;

import de.greenrobot.event.EventBus;
import jp.co.cyberagent.android.gpuimage.GPUImageFaceFilter;
import jp.co.cyberagent.android.gpuimage.GPUImageFilter;

import static com.meiyu.live.tv.audience.AudienceActivity.STATE_GAME;
import static com.meiyu.live.tv.audience.AudienceActivity.STATE_NIUNIU;

public class AnchorActivity extends BaseActivity implements OnClickListener, OnSeekBarChangeListener, lsMessageHandler {

    public static final String MEDIA_PATH = "mediaPath";
    public static final String VIDEO_RESOLUTION = "videoResolution";

    private lsMediaCapture mLSMediaCapture = null;
    private String mliveStreamingURL = null;
    private String mMixAudioFilePath = null;
    private File mMP3AppFileDirectory = null;
    private String mVideoResolution = "SD";
    private boolean mUseFilter = true;

    private Handler mHandler;

    //SDK统计相关变量
    private LSLiveStreamingParaCtx mLSLiveStreamingParaCtx = null;
    private Statistics mStatistics = null;

    //SDK日志级别相关变量
    private int mLogLevel = LS_LOG_ERROR;
    private String mLogPath = null;

    //普通模式的view
//    private LiveSurfaceView mVideoView;

    //滤镜模式的view
    private OpenGLSurfaceView mSurfaceView;

    //状态变量
    private boolean m_liveStreamingOn = false;
    private boolean m_liveStreamingInit = false;
    private boolean m_liveStreamingInitFinished = false;
    private boolean m_tryToStopLivestreaming = false;
    private boolean m_startVideoCamera = false;

    //伴音相关
    private AudioManager mAudioManager;
    private int m_mixAudioVolume;
    private HeadsetPlugReceiver mHeadsetPlugReceiver = null;
    private int mRouteMode = AUDIO_ROUTE_LOUDERSPEAKER;

    //Activity环境变量
    private Context mContext;

    private int mVideoPreviewWidth, mVideoPreviewHeight;

    private Intent mNetInfoIntent = new Intent("com.netease.netInfo");

    private Intent mAlertServiceIntent;

    private boolean mAlertServiceOn = false;

    private long mLastVideoProcessErrorAlertTime = 0;
    private long mLastAudioProcessErrorAlertTime = 0;

    private boolean mHardWareEncEnable = false;

    //视频涂鸦相关变量
    private boolean mGraffitiOn = false;//视频涂鸦开关，默认关闭，需要视频涂鸦的用户可以开启此开关
    private String mGraffitiFilePath;//视频涂鸦文件路径
    private String mGraffitiFileName = "vcloud1.bmp";//视频涂鸦文件名
    private File mGraffitiAppFileDirectory = null;
    private int mGraffitiPosX = 0;
    private int mGraffitiPosY = 0;

    //视频水印相关变量
    private Bitmap mBitmap;
    private boolean mWaterMarkOn = false;//视频水印开关，默认关闭，需要视频水印的用户可以开启此开关
    private String mWaterMarkFilePath;//视频水印文件路径
    private String mWaterMarkFileName = "logo.png";//视频水印文件名
    private File mWaterMarkAppFileDirectory = null;
    private int mWaterMarkPosX = 10;//视频水印坐标(X)
    private int mWaterMarkPosY = 10;//视频水印坐标(Y)

    //视频截图相关变量
    private String mScreenShotFilePath;//视频截图文件路径
    private String mScreenShotFileName = Constant.SnapshotFileName;//视频截图文件名

    //查询摄像头支持的采集分辨率信息相关变量
    private Thread mCameraThread;
    private Looper mCameraLooper;
    private int mCameraID = CAMERA_POSITION_BACK;//默认查询的是后置摄像头
    private Camera mCamera;

    private float mCurrentDistance;
    private float mLastDistance = -1;

    public static final int CAMERA_POSITION_BACK = 0;
    public static final int CAMERA_POSITION_FRONT = 1;

    public static final int CAMERA_ORIENTATION_PORTRAIT = 0;
    public static final int CAMERA_ORIENTATION_LANDSCAPE = 1;
    public static final int CAMERA_ORIENTATION_PORTRAIT_UPSIDEDOWN = 2;
    public static final int CAMERA_ORIENTATION_LANDSCAPE_LEFTSIDERIGHT = 3;

    public static final int LS_VIDEO_CODEC_AVC = 0;
    public static final int LS_VIDEO_CODEC_VP9 = 1;
    public static final int LS_VIDEO_CODEC_H265 = 2;

    public static final int LS_AUDIO_STREAMING_LOW_QUALITY = 0;
    public static final int LS_AUDIO_STREAMING_HIGH_QUALITY = 1;

    public static final int LS_AUDIO_CODEC_AAC = 0;
    public static final int LS_AUDIO_CODEC_SPEEX = 1;
    public static final int LS_AUDIO_CODEC_MP3 = 2;
    public static final int LS_AUDIO_CODEC_G711A = 3;
    public static final int LS_AUDIO_CODEC_G711U = 4;

    public static final int FLV = 0;
    public static final int RTMP = 1;

    public static final int HAVE_AUDIO = 0;
    public static final int HAVE_VIDEO = 1;
    public static final int HAVE_AV = 2;

    public static final int OpenQoS = 0;
    public static final int CloseQoS = 1;

    //伴音相关宏定义：
    //AUDIO_ROUTE_EARPIECE：有线耳机模式
    //AUDIO_ROUTE_LOUDERSPEAKER：外放模式
    //AUDIO_ROUTE_BLUETOOTH：蓝牙耳机模式
    public static final int AUDIO_ROUTE_EARPIECE = 0;
    public static final int AUDIO_ROUTE_LOUDERSPEAKER = 1;
    public static final int AUDIO_ROUTE_BLUETOOTH = 2;

    public static final int LS_LOG_QUIET = 0x00;            //!< log输出模式：不输出
    public static final int LS_LOG_ERROR = 1;               //!< log输出模式：输出错误
    public static final int LS_LOG_WARNING = 1 << 1;          //!< log输出模式：输出警告
    public static final int LS_LOG_INFO = 1 << 2;          //!< log输出模式：输出信息
    public static final int LS_LOG_DEBUG = 1 << 3;          //!< log输出模式：输出调试信息
    public static final int LS_LOG_DETAIL = 1 << 4;          //!< log输出模式：输出详细
    public static final int LS_LOG_RESV = 1 << 5;          //!< log输出模式：保留
    public static final int LS_LOG_LEVEL_COUNT = 6;
    public static final int LS_LOG_DEFAULT = LS_LOG_WARNING;    //!< log输出模式：默认输出警告

    //Demo广播相关变量
    private MsgReceiver msgReceiver;
    private audioMixVolumeMsgReceiver audioMixVolumeMsgReceiver;
    private EnterChatRoomData data;
    private static CreateRooomResponse createRooomResponse;

    private static final String TAG = "NeteaseLiveStream";

    private GamePopupwind gamePopupwind;

    public static void start(Activity context, CreateRooomResponse respons) {
        createRooomResponse = respons;
        Intent intent = new Intent(context, AnchorActivity.class);
//        intent.putExtra(MEDIA_PATH, "rtmp://p5886108b.live.126.net/live/15853282a0654e1788a127c7ecf374fd?wsSecret=9729a51c63c6a79ee949ec7412a5ab5c&wsTime=1468391369");
        intent.putExtra(MEDIA_PATH, respons.getPush_url());
        intent.putExtra(VIDEO_RESOLUTION, "SD");
        intent.putExtra(ROOM_ID, respons.getChatroom_id());
        intent.putExtra(ROOM_DES, respons.getDescription());
        intent.putExtra(AUTHOR_INCCOME, respons.getIncome_total());
        context.startActivity(intent);
        context.finish();
    }

    //监听设备耳机插拔的广播消息，支持有线耳机和外放模式
    public class HeadsetPlugReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.getIntExtra("state", 0) == 0) {
                    mRouteMode = AUDIO_ROUTE_LOUDERSPEAKER;//外放
                } else if (intent.getIntExtra("state", 0) == 1) {
                    mRouteMode = AUDIO_ROUTE_EARPIECE;//耳机
                }

                if (mLSMediaCapture != null) {
                    mLSMediaCapture.setAudioRouteMode(mRouteMode);
                }
            }

        }


        public void register() {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.intent.action.HEADSET_PLUG");
            registerReceiver(mHeadsetPlugReceiver, intentFilter);
        }

        public void unRegister() {
            unregisterReceiver(HeadsetPlugReceiver.this);
        }
    }

    //处理伴音MP3文件
    public void handleMP3() {

        AssetManager assetManager = getAssets();

        String[] files = null;
        try {
            files = assetManager.list("mixAudio");
        } catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }

        mMP3AppFileDirectory = getExternalFilesDir(null);
        if (mMP3AppFileDirectory == null) {
            mMP3AppFileDirectory = getFilesDir();
        }

        for (String filename : files) {
            try {
                InputStream in = assetManager.open("mixAudio/" + filename);
                File outFile = new File(mMP3AppFileDirectory, filename);
                mMixAudioFilePath = outFile.toString();
                if (!outFile.exists()) {
                    FileOutputStream out = new FileOutputStream(outFile);
                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
                Log.e("tag", "Failed to copy MP3 file", e);
            }
        }
    }

    //查询Android摄像头支持的采样分辨率相关方法（1）
    public void openCamera(final int cameraID) {
        final Semaphore lock = new Semaphore(0);
        final RuntimeException[] exception = new RuntimeException[1];
        mCameraThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                mCameraLooper = Looper.myLooper();
                try {
                    mCamera = Camera.open(cameraID);
                } catch (RuntimeException e) {
                    exception[0] = e;
                } finally {
                    lock.release();
                    Looper.loop();
                }
            }
        });
        mCameraThread.start();
        lock.acquireUninterruptibly();
    }

    //查询Android摄像头支持的采样分辨率相关方法（2）
    public void lockCamera() {
        try {
            mCamera.reconnect();
        } catch (Exception e) {
        }
    }

    //查询Android摄像头支持的采样分辨率相关方法（3）
    public void releaseCamera() {
        if (mCamera != null) {
            lockCamera();
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    //查询Android摄像头支持的采样分辨率相关方法（4）
    public List<Camera.Size> getCameraSupportSize(int cameraID) {
        openCamera(cameraID);
        if (mCamera != null) {
            Parameters param = mCamera.getParameters();
            List<Camera.Size> previewSizes = param.getSupportedPreviewSizes();
            releaseCamera();
            return previewSizes;
        }
        return null;
    }

    //视频云Demo层显示实时音视频信息的操作
    public void staticsHandle() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                Bundle bundle = msg.getData();
                int videoFrameRate = bundle.getInt("FR");
                int videoBitrate = bundle.getInt("VBR");
                int audioBitrate = bundle.getInt("ABR");
                int totalRealBitrate = bundle.getInt("TBR");

                try {
                    if (mNetInfoIntent != null) {
                        mNetInfoIntent.putExtra("videoFrameRate", videoFrameRate);
                        mNetInfoIntent.putExtra("videoBitRate", videoBitrate);
                        mNetInfoIntent.putExtra("audioBitRate", audioBitrate);
                        mNetInfoIntent.putExtra("totalRealBitrate", totalRealBitrate);

                        if (mLSLiveStreamingParaCtx.sLSVideoParaCtx.width == 1280 && mLSLiveStreamingParaCtx.sLSVideoParaCtx.height == 720) {
                            mNetInfoIntent.putExtra("resolution", 1);
                        } else if (mLSLiveStreamingParaCtx.sLSVideoParaCtx.width == 640 && mLSLiveStreamingParaCtx.sLSVideoParaCtx.height == 480) {
                            mNetInfoIntent.putExtra("resolution", 2);
                        } else if (mLSLiveStreamingParaCtx.sLSVideoParaCtx.width == 320 && mLSLiveStreamingParaCtx.sLSVideoParaCtx.height == 240) {
                            mNetInfoIntent.putExtra("resolution", 3);
                        }
                    }
                } catch (IllegalStateException e) {

                }

                sendBroadcast(mNetInfoIntent);
            }
        };
    }

    //视频水印相关方法(1)
    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }

    //视频水印相关方法(2)
    public void waterMark() {
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mWaterMarkAppFileDirectory = getExternalFilesDir(null);
        } else {
            mWaterMarkAppFileDirectory = getFilesDir();
        }

        AssetManager assetManager = getAssets();

        //拷贝水印文件到APP目录
        String[] files = null;
        File fileDirectory;

        try {
            files = assetManager.list("waterMark");
        } catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }

        if (mWaterMarkAppFileDirectory != null) {
            fileDirectory = mWaterMarkAppFileDirectory;
        } else {
            fileDirectory = Environment.getExternalStorageDirectory();
            mWaterMarkFilePath = fileDirectory + "/" + mWaterMarkFileName;
        }

        for (String filename : files) {
            try {
                InputStream in = assetManager.open("waterMark/" + filename);
                File outFile = new File(fileDirectory, filename);
                FileOutputStream out = new FileOutputStream(outFile);
                copyFile(in, out);
                mWaterMarkFilePath = outFile.toString();
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch (IOException e) {
                Log.e("tag", "Failed to copy asset file", e);
            }
        }
    }

    //视频涂鸦相关方法
    public void Graffiti() {
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mGraffitiAppFileDirectory = getExternalFilesDir(null);
        } else {
            mGraffitiAppFileDirectory = getFilesDir();
        }

        AssetManager assetManager = getAssets();

        //拷贝涂鸦文件到APP目录
        String[] files = null;
        File fileDirectory;

        try {
            files = assetManager.list("graffiti");
        } catch (IOException e) {
            Log.e("tag", "Failed to get asset file list.", e);
        }

        if (mGraffitiAppFileDirectory != null) {
            fileDirectory = mGraffitiAppFileDirectory;
        } else {
            fileDirectory = Environment.getExternalStorageDirectory();
            mGraffitiFilePath = fileDirectory + "/" + mGraffitiFileName;
        }

        for (String filename : files) {
            try {
                InputStream in = assetManager.open("graffiti/" + filename);
                File outFile = new File(fileDirectory, filename);
                FileOutputStream out = new FileOutputStream(outFile);
                copyFile(in, out);
                mGraffitiFilePath = outFile.toString();
                in.close();
                in = null;
                out.flush();
                out.close();
                out = null;
            } catch (IOException e) {
                Log.e("tag", "Failed to copy asset file", e);
            }
        }
    }

    //音视频参数设置
    public void paraSet() {

        //创建参数实例
        mLSLiveStreamingParaCtx = mLSMediaCapture.new LSLiveStreamingParaCtx();
        mLSLiveStreamingParaCtx.eHaraWareEncType = mLSLiveStreamingParaCtx.new HardWareEncEnable();
        mLSLiveStreamingParaCtx.eOutFormatType = mLSLiveStreamingParaCtx.new OutputFormatType();
        mLSLiveStreamingParaCtx.eOutStreamType = mLSLiveStreamingParaCtx.new OutputStreamType();
        mLSLiveStreamingParaCtx.sLSAudioParaCtx = mLSLiveStreamingParaCtx.new LSAudioParaCtx();
        mLSLiveStreamingParaCtx.sLSAudioParaCtx.codec = mLSLiveStreamingParaCtx.sLSAudioParaCtx.new LSAudioCodecType();
        mLSLiveStreamingParaCtx.sLSVideoParaCtx = mLSLiveStreamingParaCtx.new LSVideoParaCtx();
        mLSLiveStreamingParaCtx.sLSVideoParaCtx.codec = mLSLiveStreamingParaCtx.sLSVideoParaCtx.new LSVideoCodecType();
        mLSLiveStreamingParaCtx.sLSVideoParaCtx.cameraPosition = mLSLiveStreamingParaCtx.sLSVideoParaCtx.new CameraPosition();
        mLSLiveStreamingParaCtx.sLSVideoParaCtx.interfaceOrientation = mLSLiveStreamingParaCtx.sLSVideoParaCtx.new CameraOrientation();
        mLSLiveStreamingParaCtx.sLSQoSParaCtx = mLSLiveStreamingParaCtx.new LSQoSParaCtx();

        if (!mLSLiveStreamingParaCtx.eHaraWareEncType.hardWareEncEnable && mWaterMarkOn) {
            waterMark();
        }

        if (!mLSLiveStreamingParaCtx.eHaraWareEncType.hardWareEncEnable && mGraffitiOn) {
            Graffiti();
        }

        //设置摄像头信息，并开始本地视频预览
        mLSLiveStreamingParaCtx.sLSVideoParaCtx.cameraPosition.cameraPosition = CAMERA_POSITION_BACK;//默认后置摄像头，用户可以根据需要调整

        //输出格式：视频、音频和音视频
        mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType = HAVE_AV;//默认音视频推流

        //输出封装格式
        mLSLiveStreamingParaCtx.eOutFormatType.outputFormatType = RTMP;//默认RTMP推流

        //摄像头参数配置
        mLSLiveStreamingParaCtx.sLSVideoParaCtx.interfaceOrientation.interfaceOrientation = CAMERA_ORIENTATION_PORTRAIT;//默认竖屏

        //音频编码参数配置
        mLSLiveStreamingParaCtx.sLSAudioParaCtx.samplerate = 44100;
        mLSLiveStreamingParaCtx.sLSAudioParaCtx.bitrate = 64000;
        mLSLiveStreamingParaCtx.sLSAudioParaCtx.frameSize = 2048;
        mLSLiveStreamingParaCtx.sLSAudioParaCtx.audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
        mLSLiveStreamingParaCtx.sLSAudioParaCtx.channelConfig = AudioFormat.CHANNEL_IN_MONO;
        mLSLiveStreamingParaCtx.sLSAudioParaCtx.codec.audioCODECType = LS_AUDIO_CODEC_AAC;

        //硬件编码参数设置
        mLSLiveStreamingParaCtx.eHaraWareEncType.hardWareEncEnable = mHardWareEncEnable;//默认关闭硬件编码

        //网络QoS开关
        mLSLiveStreamingParaCtx.sLSQoSParaCtx.qosType = OpenQoS;//默认打开QoS

        //视频编码参数配置，视频码率可以由用户任意设置，视频分辨率按照如下表格设置
        //采集分辨率     编码分辨率     建议码率
        //1280x720     1280x720     1500kbps
        //1280x720     960x540      800kbps
        //960x720      960x720      1000kbps
        //960x720      960x540      800kbps
        //960x540      960x540      800kbps
        //640x480      640x480      600kbps
        //640x480      640x360      500kbps
        //320x240      320x240      250kbps
        //320x240      320x180      200kbps

        //如下是编码分辨率等信息的设置
        if (mVideoResolution.equals("HD")) {
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.fps = 20;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.bitrate = 1500000;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.codec.videoCODECType = LS_VIDEO_CODEC_AVC;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.width = 1280;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.height = 720;
        } else if (mVideoResolution.equals("SD")) {
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.fps = 20;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.bitrate = 600000;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.codec.videoCODECType = LS_VIDEO_CODEC_AVC;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.width = 640;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.height = 480;
        } else {
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.fps = 15;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.bitrate = 250000;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.codec.videoCODECType = LS_VIDEO_CODEC_AVC;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.width = 320;
            mLSLiveStreamingParaCtx.sLSVideoParaCtx.height = 240;
        }
    }

    private void startLive() {
        if (!m_liveStreamingOn) {
            startAV();
        }
    }


    //获取日志文件路径
    public void getLogPath() {
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                mLogPath = Environment.getExternalStorageDirectory() + "/log/";
            }
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
    }

    //切换前后摄像头
    private void switchCamera() {
        if (mLSMediaCapture != null) {
            mLSMediaCapture.switchCamera();
        }
    }

    //开始直播
    private void startAV() {
        if (mLSMediaCapture != null && m_liveStreamingInitFinished) {

            //7、设置视频水印参数（可选）
            if (!mHardWareEncEnable && (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AV || mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_VIDEO)) {
                mLSMediaCapture.setWaterMarkPara(mWaterMarkOn, mWaterMarkFilePath, mWaterMarkPosX, mWaterMarkPosY);
            }

            //8、开始直播
            mLSMediaCapture.startLiveStreaming();
            m_liveStreamingOn = true;

            //9、设置视频涂鸦参数（可选）
            if (!mHardWareEncEnable && mGraffitiOn && (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AV || mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_VIDEO)) {
                FileInputStream is = null;
                try {
                    is = new FileInputStream(mGraffitiFilePath);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Bitmap bitmap = BitmapFactory.decodeStream(is);

                int mWidth = bitmap.getWidth();
                int mHeight = bitmap.getHeight();
                int[] mIntArray = new int[mWidth * mHeight];

                // Copy pixel data from the Bitmap into the 'intArray' array
                bitmap.getPixels(mIntArray, 0, mWidth, 0, 0, mWidth, mHeight);

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Log.e(TAG, "error : ", e);
                }

                mLSMediaCapture.setGraffitiPara(mIntArray, mWidth, mHeight, mGraffitiPosX, mGraffitiPosY, mGraffitiOn);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
        //动态注册广播接收器，接收Service的消息
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("AudioMix");
        registerReceiver(msgReceiver, intentFilter);

        //动态注册广播接收器，接收Service的消息
        audioMixVolumeMsgReceiver = new audioMixVolumeMsgReceiver();
        IntentFilter audioMixVolumeIntentFilter = new IntentFilter();
        audioMixVolumeIntentFilter.addAction("AudioMixVolume");
        registerReceiver(audioMixVolumeMsgReceiver, audioMixVolumeIntentFilter);

        //应用运行时，保持屏幕高亮，不锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //从直播设置页面获取推流URL和分辨率信息
        //alert1用于检测设备SDK版本是否符合开启滤镜要求，alert2用于检测设备的硬件编码模块（与滤镜相关）是否正常
        mliveStreamingURL = getIntent().getStringExtra(MEDIA_PATH);
        mVideoResolution = getIntent().getStringExtra(VIDEO_RESOLUTION);
        room_id = getIntent().getLongExtra(ROOM_ID, 0);
        author_income = getIntent().getIntExtra(AUTHOR_INCCOME, 0);
        room_des = getIntent().getStringExtra(ROOM_DES);

        //获取摄像头支持的分辨率信息，根据这个信息，用户可以选择合适的视频preview size和encode size
        //!!!!注意，用户在设置视频采集分辨率和编码分辨率的时候必须预先获取摄像头支持的采集分辨率，并设置摄像头支持的采集分辨率，否则会造成不可预知的错误，导致直播推流失败和SDK崩溃
        //用户可以采用下面的方法(getCameraSupportSize)，获取摄像头支持的采集分辨率列表
        //获取分辨率之后，用户可以按照下表选择性设置采集分辨率和编码分辨率(注意：一定要Android设备支持该种采集分辨率才可以设置，否则会造成不可预知的错误，导致直播推流失败和SDK崩溃)

        //采集分辨率     编码分辨率     建议码率
        //1280x720     1280x720     1500kbps
        //1280x720     960x540      800kbps
        //960x720      960x720      1000kbps
        //960x720      960x540      800kbps
        //960x540      960x540      800kbps
        //640x480      640x480      600kbps
        //640x480      640x360      500kbps
        //320x240      320x240      250kbps
        //320x240      320x180      200kbps


        //用户需要分别检查前后摄像头支持的分辨率，设置前后摄像头都支持的分辨率，保障在切换摄像头的过程中不会出错
//        List<Camera.Size> backCameraSupportSize = getCameraSupportSize(CAMERA_POSITION_BACK);
//        List<Camera.Size> frontCameraSupportSize = getCameraSupportSize(CAMERA_POSITION_FRONT);
//
//        if (backCameraSupportSize != null && backCameraSupportSize.size() != 0) {
//			for (Size size : backCameraSupportSize) {
//				Log.i(TAG, "backCameraSupportSize " + " is " + size.width + "x" + size.height);
//			}
//		}
//
//        if (frontCameraSupportSize != null && frontCameraSupportSize.size() != 0) {
//			for (Size size : frontCameraSupportSize) {
//				Log.i(TAG, "frontCameraSupportSize " + " is " + size.width + "x" + size.height);
//			}
//		}


        if (mVideoResolution.equals("HD")) {
            mVideoPreviewWidth = 1280;
            mVideoPreviewHeight = 720;
        } else if (mVideoResolution.equals("SD")) {
            mVideoPreviewWidth = 640;
            mVideoPreviewHeight = 480;
        } else {
            mVideoPreviewWidth = 320;
            mVideoPreviewHeight = 240;
        }

        m_liveStreamingOn = false;
        m_tryToStopLivestreaming = false;

        mContext = this;

        //伴音相关操作，获取设备音频播放service
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        //拷贝MP3文件到APP目录
        handleMP3();

        //以下为SDK调用主要步骤，请用户参考使用
        //1、创建直播实例
        mLSMediaCapture = new lsMediaCapture(this, mContext, mVideoPreviewWidth, mVideoPreviewHeight, mUseFilter);

        //2、设置直播参数
        paraSet();

        //3、发送统计数据到网络信息界面（Demo层实现，用户不需要添加该操作）
        staticsHandle();

        setContentView(R.layout.activity_anchor);
//        mVideoView = (LiveSurfaceView) findViewById(R.id.videoview);
        mSurfaceView = (OpenGLSurfaceView) findViewById(R.id.gl_surfaceView);

        //5、设置日志级别和日志文件路径
        getLogPath();
        if (mLSMediaCapture != null) {
            mLSMediaCapture.setTraceLevel(mLogLevel, mLogPath);
        }

        //6、设置视频预览参数
//        mVideoView.setPreviewSize(mVideoPreviewWidth, mVideoPreviewHeight);
        mSurfaceView.setPreviewSize(mVideoPreviewWidth, mVideoPreviewHeight);

        if (mLSMediaCapture != null) {
            boolean ret = false;

            //7、开启视频预览
            if (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AV || mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_VIDEO) {
//                mLSMediaCapture.startVideoPreview(mVideoView, mLSLiveStreamingParaCtx.sLSVideoParaCtx.cameraPosition.cameraPosition);
//                m_startVideoCamera = true;
                mLSLiveStreamingParaCtx.sLSVideoParaCtx.cameraPosition.cameraPosition = CAMERA_POSITION_FRONT;//设置默认为前置摄像头
                mLSMediaCapture.startVideoPreviewOpenGL(mSurfaceView, mLSLiveStreamingParaCtx.sLSVideoParaCtx.cameraPosition.cameraPosition);
                m_startVideoCamera = true;
            }

            //8、初始化直播推流
            ret = mLSMediaCapture.initLiveStream(mliveStreamingURL, mLSLiveStreamingParaCtx);

            if (ret) {
                m_liveStreamingInit = true;
                m_liveStreamingInitFinished = true;
            } else {
                m_liveStreamingInit = true;
                m_liveStreamingInitFinished = false;
            }
        }

        //10、给广播绑定响应的过滤器（Demo层实现，用户不需要添加该操作）
        mHeadsetPlugReceiver = new HeadsetPlugReceiver();
        mHeadsetPlugReceiver.register();

        init();
        initIM();
        getGiftlistData();
        getCoinsData();
        setState(STATE_NORMAL);
    }

    @Override
    protected void onDestroy() {
        stopAddRobotTast();
        gamePopupwind.destory();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }

        if (m_liveStreamingInit) {
            m_liveStreamingInit = false;
        }

        //伴音相关Receiver取消注册
        unregisterReceiver(msgReceiver);
        unregisterReceiver(audioMixVolumeMsgReceiver);
        unregisterReceiver(mHeadsetPlugReceiver);

        //Demo层报警信息操作的销毁
        if (mAlertServiceOn) {
            mAlertServiceIntent = new Intent(AnchorActivity.this, AlertService.class);
            stopService(mAlertServiceIntent);
            mAlertServiceOn = false;
        }

        //停止直播调用相关API接口
        if (mLSMediaCapture != null && m_liveStreamingOn) {

            //停止直播，释放资源
            mLSMediaCapture.stopLiveStreaming();

            //如果音视频或者单独视频直播，需要关闭视频预览
            if (m_startVideoCamera) {
                mLSMediaCapture.stopVideoPreview();
                mLSMediaCapture.destroyVideoPreview();
            }

            //反初始化推流实例，当它与stopLiveStreaming连续调用时，参数为false
            mLSMediaCapture.uninitLsMediaCapture(false);
            mLSMediaCapture = null;
        } else if (mLSMediaCapture != null && m_startVideoCamera) {
            mLSMediaCapture.stopVideoPreview();
            mLSMediaCapture.destroyVideoPreview();

            //反初始化推流实例，当它不与stopLiveStreaming连续调用时，参数为true
            mLSMediaCapture.uninitLsMediaCapture(true);
            mLSMediaCapture = null;
        } else if (!m_liveStreamingInitFinished) {
            //反初始化推流实例，当它不与stopLiveStreaming连续调用时，参数为true
            mLSMediaCapture.uninitLsMediaCapture(true);
        }

        if (m_liveStreamingOn) {
            m_liveStreamingOn = false;
        }

        super.onDestroy();
    }

    protected void onPause() {
        if (mLSMediaCapture != null) {
            if (!m_tryToStopLivestreaming && m_liveStreamingOn) {
//                if (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AV || mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_VIDEO) {
//                    //非滤镜模式下继续视频推流，推固定图像
//                    mLSMediaCapture.resumeVideoEncode();
//                }
                if (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AUDIO) {
                    //释放音频采集资源
                    mLSMediaCapture.stopAudioRecord();
                }
            }
        }
        super.onPause();
    }

    protected void onRestart() {
        if (mLSMediaCapture != null) {
//            if (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AV || mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_VIDEO) {
//                //非滤镜模式下关闭推流固定图像，正常推流
//                mLSMediaCapture.stopVideoEncode();
//            }
            if (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AUDIO) {
                //关闭推流静音帧
                mLSMediaCapture.stopAudioEncode();
            }
        }
        super.onRestart();
    }

    protected void onResume() {
        super.onResume();
    }

    protected void onStart() {
        super.onStart();
    }

    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {
        if (mLSMediaCapture != null) {
            mLSMediaCapture.setFilterStrength(progress);
        }
    }

    //处理SDK抛上来的异常和事件，用户需要在这里监听各种消息，进行相应的处理。
    //例如监听断网消息，用户根据断网消息进行直播重连
    //注意：直播重连请使用restartLiveStream，在网络带宽较低导致发送码率帧率降低时，可以调用这个接口重启直播，改善直播质量
    //在网络断掉的时候（用户可以监听 MSG_RTMP_URL_ERROR 和 MSG_BAD_NETWORK_DETECT ），用户不可以立即调用改接口，而是应该在网络重新连接以后，主动调用这个接口。
    //如果在网络没有重新连接便调用这个接口，直播将不会重启
    @Override
    public void handleMessage(int msg, Object object) {
        switch (msg) {
            case MSG_INIT_LIVESTREAMING_OUTFILE_ERROR://初始化直播出错
            case MSG_INIT_LIVESTREAMING_VIDEO_ERROR:
            case MSG_INIT_LIVESTREAMING_AUDIO_ERROR: {
                if (m_liveStreamingInit) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alert", "MSG_INIT_LIVESTREAMING_ERROR");
                    Intent intent = new Intent(AnchorActivity.this, AlertService.class);
                    intent.putExtras(bundle);
                    startService(intent);
                    mAlertServiceOn = true;
                }
                break;
            }
            case MSG_START_LIVESTREAMING_ERROR://开始直播出错
            {
                break;
            }
            case MSG_STOP_LIVESTREAMING_ERROR://停止直播出错
            {
                if (m_liveStreamingOn) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alert", "MSG_STOP_LIVESTREAMING_ERROR");
                    Intent intent = new Intent(AnchorActivity.this, AlertService.class);
                    intent.putExtras(bundle);
                    startService(intent);
                    mAlertServiceOn = true;
                }
                break;
            }
            case MSG_AUDIO_PROCESS_ERROR://音频处理出错
            {
                if (m_liveStreamingOn && System.currentTimeMillis() - mLastAudioProcessErrorAlertTime >= 10000) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alert", "MSG_AUDIO_PROCESS_ERROR");
                    Intent intent = new Intent(AnchorActivity.this, AlertService.class);
                    intent.putExtras(bundle);
                    startService(intent);
                    mAlertServiceOn = true;
                    mLastAudioProcessErrorAlertTime = System.currentTimeMillis();
                }

                break;
            }
            case MSG_VIDEO_PROCESS_ERROR://视频处理出错
            {
                if (m_liveStreamingOn && System.currentTimeMillis() - mLastVideoProcessErrorAlertTime >= 10000) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alert", "MSG_VIDEO_PROCESS_ERROR");
                    Intent intent = new Intent(AnchorActivity.this, AlertService.class);
                    intent.putExtras(bundle);
                    startService(intent);
                    mAlertServiceOn = true;
                    mLastVideoProcessErrorAlertTime = System.currentTimeMillis();
                }
                break;
            }
            case MSG_START_PREVIEW_ERROR://视频预览出错，可能是获取不到camera的使用权限
            {
                //Log.i(TAG, "test: in handleMessage, MSG_START_PREVIEW_ERROR");
                break;
            }
            case MSG_AUDIO_RECORD_ERROR://音频采集出错，获取不到麦克风的使用权限
            {
                //Log.i(TAG, "test: in handleMessage, MSG_AUDIO_RECORD_ERROR");
                break;
            }
            case MSG_RTMP_URL_ERROR://断网消息
            {
                //Log.i(TAG, "test: in handleMessage, MSG_RTMP_URL_ERROR");
                break;
            }
            case MSG_URL_NOT_AUTH://直播URL非法，URL格式不符合视频云要求
            {
                if (m_liveStreamingInit) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alert", "MSG_URL_NOT_AUTH");
                    Intent intent = new Intent(AnchorActivity.this, AlertService.class);
                    intent.putExtras(bundle);
                    startService(intent);
                    mAlertServiceOn = true;
                }
                break;
            }
            case MSG_SEND_STATICS_LOG_ERROR://发送统计信息出错
            {
                //Log.i(TAG, "test: in handleMessage, MSG_SEND_STATICS_LOG_ERROR");
                break;
            }
            case MSG_SEND_HEARTBEAT_LOG_ERROR://发送心跳信息出错
            {
                //Log.i(TAG, "test: in handleMessage, MSG_SEND_HEARTBEAT_LOG_ERROR");
                break;
            }
            case MSG_AUDIO_SAMPLE_RATE_NOT_SUPPORT_ERROR://音频采集参数不支持
            {
                //Log.i(TAG, "test: in handleMessage, MSG_AUDIO_SAMPLE_RATE_NOT_SUPPORT_ERROR");
                break;
            }
            case MSG_AUDIO_PARAMETER_NOT_SUPPORT_BY_HARDWARE_ERROR://音频参数不支持
            {
                //Log.i(TAG, "test: in handleMessage, MSG_AUDIO_PARAMETER_NOT_SUPPORT_BY_HARDWARE_ERROR");
                break;
            }
            case MSG_NEW_AUDIORECORD_INSTANCE_ERROR://音频实例初始化出错
            {
                //Log.i(TAG, "test: in handleMessage, MSG_NEW_AUDIORECORD_INSTANCE_ERROR");
                break;
            }
            case MSG_AUDIO_START_RECORDING_ERROR://音频采集出错
            {
                //Log.i(TAG, "test: in handleMessage, MSG_AUDIO_START_RECORDING_ERROR");
                break;
            }
            case MSG_QOS_TO_STOP_LIVESTREAMING://网络QoS极差，视频码率档次降到最低
            {
                //Log.i(TAG, "test: in handleMessage, MSG_QOS_TO_STOP_LIVESTREAMING");
                break;
            }
            case MSG_HW_VIDEO_PACKET_ERROR://视频硬件编码出错反馈消息
            {
                if (m_liveStreamingOn) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alert", "MSG_HW_VIDEO_PACKET_ERROR");
                    Intent intent = new Intent(AnchorActivity.this, AlertService.class);
                    intent.putExtras(bundle);
                    startService(intent);
                    mAlertServiceOn = true;
                }
                break;
            }
            case MSG_WATERMARK_INIT_ERROR://视频水印操作初始化出错
            {
                break;
            }
            case MSG_WATERMARK_PIC_OUT_OF_VIDEO_ERROR://视频水印图像超出原始视频出错
            {
                //Log.i(TAG, "test: in handleMessage: MSG_WATERMARK_PIC_OUT_OF_VIDEO_ERROR");
                break;
            }
            case MSG_WATERMARK_PARA_ERROR://视频水印参数设置出错
            {
                //Log.i(TAG, "test: in handleMessage: MSG_WATERMARK_PARA_ERROR");
                break;
            }
            case MSG_CAMERA_PREVIEW_SIZE_NOT_SUPPORT_ERROR://camera采集分辨率不支持
            {
                //Log.i(TAG, "test: in handleMessage: MSG_CAMERA_PREVIEW_SIZE_NOT_SUPPORT_ERROR");
                break;
            }
            case MSG_START_PREVIEW_FINISHED://camera采集预览完成
            {
                //Log.i(TAG, "test: MSG_START_PREVIEW_FINISHED");

                //如果是音视频直播或者视频直播，视频preview之后才允许开始直播
                if (mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_AV || mLSLiveStreamingParaCtx.eOutStreamType.outputStreamType == HAVE_VIDEO) {
                    startLive();
                }
                break;
            }
            case MSG_START_LIVESTREAMING_FINISHED://开始直播完成
            {
                startCaptureTask();
                switchFilterTo(new GPUImageFaceFilter());
                break;
            }
            case MSG_STOP_LIVESTREAMING_FINISHED://停止直播完成
            {
                stopCaptureTask();
                //Log.i(TAG, "test: MSG_STOP_LIVESTREAMING_FINISHED");
                {
//                    mIntentLiveStreamingStopFinished.putExtra("LiveStreamingStopFinished", 1);
//                    sendBroadcast(mIntentLiveStreamingStopFinished);
                }

//				  mIntentLiveStreamingStopFinished = null;
//				  mStatistics = null;
//				  mHandler.removeCallbacksAndMessages(null);
//				  mHandler = null;

                break;
            }
            case MSG_STOP_VIDEO_CAPTURE_FINISHED: {
                //Log.i(TAG, "test: in handleMessage: MSG_STOP_VIDEO_CAPTURE_FINISHED");
                if (!m_tryToStopLivestreaming && mLSMediaCapture != null) {
                    //继续视频推流，推最后一帧图像
                    mLSMediaCapture.resumeVideoEncode();
                }
                break;
            }
            case MSG_STOP_RESUME_VIDEO_CAPTURE_FINISHED: {
                //Log.i(TAG, "test: in handleMessage: MSG_STOP_RESUME_VIDEO_CAPTURE_FINISHED");
                //开启视频preview
                if (mLSMediaCapture != null) {
                    mLSMediaCapture.resumeVideoPreview();
                    m_liveStreamingOn = true;
                    //开启视频推流，推正常帧
                    mLSMediaCapture.startVideoLiveStream();
                }
                break;
            }
            case MSG_STOP_AUDIO_CAPTURE_FINISHED: {
                //Log.i(TAG, "test: in handleMessage: MSG_STOP_AUDIO_CAPTURE_FINISHED");
                if (!m_tryToStopLivestreaming && mLSMediaCapture != null) {
                    //继续音频推流，推静音帧
                    mLSMediaCapture.resumeAudioEncode();
                }
                break;
            }
            case MSG_STOP_RESUME_AUDIO_CAPTURE_FINISHED: {
                //Log.i(TAG, "test: in handleMessage: MSG_STOP_RESUME_AUDIO_CAPTURE_FINISHED");
                //开启音频推流，推正常帧
                mLSMediaCapture.startAudioLiveStream();
                break;
            }
            case MSG_SWITCH_CAMERA_FINISHED://切换摄像头完成
            {
                int cameraId = (Integer) object;//切换之后的camera id
                break;
            }
            case MSG_SEND_STATICS_LOG_FINISHED://发送统计信息完成
            {
                //Log.i(TAG, "test: in handleMessage, MSG_SEND_STATICS_LOG_FINISHED");
                break;
            }
            case MSG_SERVER_COMMAND_STOP_LIVESTREAMING://服务器下发停止直播的消息反馈，暂时不使用
            {
                //Log.i(TAG, "test: in handleMessage, MSG_SERVER_COMMAND_STOP_LIVESTREAMING");
                break;
            }
            case MSG_GET_STATICS_INFO://获取统计信息的反馈消息
            {
                //Log.i(TAG, "test: in handleMessage, MSG_GET_STATICS_INFO");

                //显示统计信息
//                Message message = new Message();
//                mStatistics = (Statistics) object;
//
//                Bundle bundle = new Bundle();
//                bundle.putInt("FR", mStatistics.videoSendFrameRate);
//                bundle.putInt("VBR", mStatistics.videoSendBitRate);
//                bundle.putInt("ABR", mStatistics.audioSendBitRate);
//                bundle.putInt("TBR", mStatistics.totalRealSendBitRate);
//                message.setData(bundle);
//
//                if (mHandler != null) {
//                    mHandler.sendMessage(message);
//                }
                break;
            }
            case MSG_BAD_NETWORK_DETECT://如果连续一段时间（10s）实际推流数据为0，会反馈这个错误消息
            {
                //Log.i(TAG, "test: in handleMessage, MSG_BAD_NETWORK_DETECT");
                break;
            }
            case MSG_SCREENSHOT_FINISHED://视频截图完成后的消息反馈
            {
                //Log.i(TAG, "test: in handleMessage, MSG_SCREENSHOT_FINISHED, buffer is " + (byte[]) object);
//                getScreenShotByteBuffer((byte[]) object);
                break;
            }
            case MSG_SET_CAMERA_ID_ERROR://设置camera出错（对于只有一个摄像头的设备，如果调用了不存在的摄像头，会反馈这个错误消息）
            {
                //Log.i(TAG, "test: in handleMessage, MSG_SET_CAMERA_ID_ERROR");
                break;
            }
            case MSG_SET_GRAFFITI_ERROR://设置涂鸦出错消息反馈
            {
                //Log.i(TAG, "test: in handleMessage, MSG_SET_GRAFFITI_ERROR");
                break;
            }
            case MSG_MIX_AUDIO_FINISHED://伴音一首MP3歌曲结束后的反馈
            {
                //Log.i(TAG, "test: in handleMessage, MSG_MIX_AUDIO_FINISHED");
                break;
            }
            case MSG_URL_FORMAT_NOT_RIGHT://推流url格式不正确
            {
                //Log.i(TAG, "test: in handleMessage, MSG_URL_FORMAT_NOT_RIGHT");
                break;
            }
            case MSG_URL_IS_EMPTY://推流url为空
            {
                //Log.i(TAG, "test: in handleMessage, MSG_URL_IS_EMPTY");
                break;
            }
        }
    }

    //获取截屏图像的数据
    public void getScreenShotByteBuffer(byte[] screenShotByteBuffer) {
        FileOutputStream outStream = null;
        String screenShotFilePath = mScreenShotFilePath + "/" + mScreenShotFileName;
        if (screenShotFilePath != null) {
            try {
                if (screenShotFilePath != null) {

                    outStream = new FileOutputStream(String.format(screenShotFilePath));
                    outStream.write(screenShotByteBuffer);
                    outStream.close();
                    //将截图上传到服务器
                    postCaptureData();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }
        }
    }


    //Demo层视频缩放和摄像头对焦操作相关方法
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //Log.i(TAG, "test: down!!!");
                //调用摄像头对焦操作相关API
                if (mLSMediaCapture != null) {
                    mLSMediaCapture.setCameraFocus();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                //Log.i(TAG, "test: move!!!");
                /**
                 * 首先判断按下手指的个数是不是大于两个。
                 * 如果大于两个则执行以下操作（即图片的缩放操作）。
                 */
                if (event.getPointerCount() >= 2) {

                    float offsetX = event.getX(0) - event.getX(1);
                    float offsetY = event.getY(0) - event.getY(1);
                    /**
                     * 原点和滑动后点的距离差
                     */
                    mCurrentDistance = (float) Math.sqrt(offsetX * offsetX + offsetY * offsetY);
                    if (mLastDistance < 0) {
                        mLastDistance = mCurrentDistance;
                    } else {
                        /**
                         * 如果当前滑动的距离（currentDistance）比最后一次记录的距离（lastDistance）相比大于5英寸（也可以为其他尺寸），
                         * 那么现实图片放大
                         */
                        if (mCurrentDistance - mLastDistance > 5) {
                            //Log.i(TAG, "test: 放大！！！");
                            if (mLSMediaCapture != null) {
                                mLSMediaCapture.setCameraZoomPara(true);
                            }

                            mLastDistance = mCurrentDistance;
                            /**
                             * 如果最后的一次记录的距离（lastDistance）与当前的滑动距离（currentDistance）相比小于5英寸，
                             * 那么图片缩小。
                             */
                        } else if (mLastDistance - mCurrentDistance > 5) {
                            //Log.i(TAG, "test: 缩小！！！");
                            if (mLSMediaCapture != null) {
                                mLSMediaCapture.setCameraZoomPara(false);
                            }

                            mLastDistance = mCurrentDistance;
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                //Log.i(TAG, "test: up!!!");
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if (currentState != STATE_NORMAL) {
            setState(STATE_NORMAL);
        } else {
            m_tryToStopLivestreaming = true;
            finishLive();
        }
    }

    //用于接收Service发送的消息，伴音开关
    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int audioMixMsg = intent.getIntExtra("AudioMixMSG", 0);
            mMixAudioFilePath = mMP3AppFileDirectory.toString() + "/" + intent.getStringExtra("AudioMixFilePathMSG");

            //伴音开关的控制
            if (audioMixMsg == 1) {
                if (mMixAudioFilePath.isEmpty())
                    return;

                if (mLSMediaCapture != null) {
                    mLSMediaCapture.setMixIntensity(m_mixAudioVolume);
                    mLSMediaCapture.setAudioRouteMode(mRouteMode);
                    mLSMediaCapture.startPlayMusic(mMixAudioFilePath);
                }
            } else if (audioMixMsg == 2) {
                if (mLSMediaCapture != null) {
                    mLSMediaCapture.resumePlayMusic();
                }
            } else if (audioMixMsg == 3) {
                if (mLSMediaCapture != null) {
                    mLSMediaCapture.pausePlayMusic();
                }
            } else if (audioMixMsg == 4) {
                if (mLSMediaCapture != null) {
                    mLSMediaCapture.stopPlayMusic();
                }
            }
        }
    }

    //用于接收Service发送的消息，伴音音量
    public class audioMixVolumeMsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int audioMixVolumeMsg = intent.getIntExtra("AudioMixVolumeMSG", 0);

            //伴音音量的控制
            if (mRouteMode == AUDIO_ROUTE_LOUDERSPEAKER)//外放模式
            {
                int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                int maxStreamVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

                streamVolume = audioMixVolumeMsg * maxStreamVolume / 10;
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, streamVolume, 1);
            } else if (mRouteMode == AUDIO_ROUTE_EARPIECE)//耳机模式
            {
                mLSMediaCapture.setMixIntensity(audioMixVolumeMsg);
            }
        }
    }


    ////////////////////////////
    //和观看直播界面类似的功能//
    ////////////////////////////

    public final static String ROOM_ID = "room_id";
    public final static String AUTHOR_INCCOME = "author_income";
    public final static String AUTHOR_NAME = "author_name";
    public final static String AUTHOR_AVATAR = "author_avatar";
    public final static String ROOM_DES = "room_des";

    public final static int STATE_NORMAL = 0;
    public final static int STATE_INPUT_MESSAGE = 1;
    public final static int STATE_PRIVATE_MESSAGE = 2;
    public final static int STATE_SELECT_GIFT = 3;
    public final static int STATE_BEAUTY_SETTING = 4;

    private static final int REQUEST_FINISH = 1;

    private LayoutInflater inflater;

    private long room_id; //房间id
    private String room_des; //房间描述
    private int author_income; //主播收入
    private int myCoins;
    private List<RoomMessage> roomMessageList = new ArrayList<>();

    private View btn_chat, btn_message, btn_gift, btn_share, iv_message_flag, btn_game;
    private View layout_bottom_btn;
    private TvTitleView tvTitleView;
    private GiftGifShowView giftGifShowView;
    private ToolsView toolsView;
    private GiftShowView giftShowView;
    private DanmuShowView danmuShowView;
    private InputView inputView;
    private PrivateMessageView privateMessageView;
    private GiftSendView giftSendView;
    private GameListView gameListView;
    private BeautySettingView beautySettingView;
    private ListView listView_message;
    private RoomMessageAdapter messageAdapter;
    private ChatRoomMessageParser chatRoomMessageParser;
    private ShareDialog shareDialog;
    private RoomManageListPopwindow roomManageListPopwindow;
    private AtmosphereView atmosphere_view;
    private ImageView btn_switch_camera;

    private int currentState = STATE_NORMAL;

    private void init() {
        inflater = LayoutInflater.from(this);
        mScreenShotFilePath = getExternalCacheDir().getAbsolutePath();

        btn_chat = findViewById(R.id.btn_chat);
        btn_chat.setOnClickListener(this);
        btn_message = findViewById(R.id.btn_message);
        btn_message.setOnClickListener(this);
        btn_gift = findViewById(R.id.btn_gift);
        btn_gift.setOnClickListener(this);
        btn_share = findViewById(R.id.btn_share);
        btn_share.setOnClickListener(this);
        btn_switch_camera = (ImageView) findViewById(R.id.btn_switch);
        btn_switch_camera.setOnClickListener(this);
        btn_game = findViewById(R.id.btn_game);
        btn_game.setOnClickListener(this);
        iv_message_flag = findViewById(R.id.iv_message_flag);

        tvTitleView = (TvTitleView) findViewById(R.id.view_tvtitle);
        tvTitleView.setOnTvTitleViewListener(new TvTitleView.OnTvTitleViewClickListener() {
            @Override
            public void onBack() {
                finishLive();
            }

            @Override
            public void onClickPrivateMessage(String neteaseId) {

            }

            @Override
            public void onClickManage() {
                if (roomManageListPopwindow == null) {
                    roomManageListPopwindow = new RoomManageListPopwindow(AnchorActivity.this);
                    roomManageListPopwindow.setIsAnchor(true);
                    roomManageListPopwindow.updateData(room_id);
                }
                if (roomManageListPopwindow.isShowing()) {
                    roomManageListPopwindow.dismiss();
                } else {
                    int margin = DisplayUtils.dpToPixel(getApplicationContext(), 20);
                    roomManageListPopwindow.showAsDropDown(tvTitleView.getLayoutMoney(), margin, margin);
                }
            }
        });
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            tvTitleView.setAuthorInfo(personalInfo.getName(), personalInfo.getAvatar());
            tvTitleView.setAnchorId(personalInfo.getId());
            tvTitleView.setCuteCode(personalInfo.getCuteCode() + "");
        }
        tvTitleView.setNeteaseId(UserConfig.getInstance().getNet_ease());
        tvTitleView.setCoins(author_income);
        tvTitleView.setShowFollowButton(false);
        giftGifShowView = (GiftGifShowView) findViewById(R.id.giftGifShowView);

        toolsView = (ToolsView) findViewById(R.id.view_tools);
        toolsView.setListener(new ToolsView.OnToolButtonClickListener() {
            @Override
            public void onClickBeauty() {
                setState(STATE_BEAUTY_SETTING);
            }
        });

        layout_bottom_btn = findViewById(R.id.layout_bottom_btn);
        giftGifShowView = (GiftGifShowView) findViewById(R.id.giftGifShowView);
        giftShowView = (GiftShowView) findViewById(R.id.giftShowView);
        giftShowView.setOnGiftShowListener(new GiftShowView.OnGiftShowListener() {
            @Override
            public void onGiftShowFinish(Gift gift) {
                final RoomMessage roomMessage = new RoomMessage();
                roomMessage.setType(1);
                roomMessage.setName(gift.name);
                roomMessage.setAvatar(gift.icon);
                roomMessage.setUser_id(gift.user_id);
                roomMessage.setNet_ease_id(gift.net_ease_id);
                roomMessage.setLevel(gift.level);
                if (gift.gift_count == 1) {
                    roomMessage.setContent("送了一个" + gift.gift_name);
                } else {
                    roomMessage.setContent("送了" + gift.gift_count + "个" + gift.gift_name);
                }
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }
        });
        danmuShowView = (DanmuShowView) findViewById(R.id.danmuShowView);
        inputView = (InputView) findViewById(R.id.inputView);
        inputView.setOnInputListener(new InputView.OnInputListener() {
            @Override
            public void onSend(String text, boolean isDanmu) {
                if (isDanmu) {
                    sendDanmuMessage(text);
                } else {
                    sendRoomMessage(text, ChatRoomMessageParser.TYPE_ROOM_MESSAGE);
                }
                setState(STATE_NORMAL);
            }
        });
        privateMessageView = (PrivateMessageView) findViewById(R.id.privateMessageView);
        privateMessageView.setListener(new PrivateMessageView.PrivateMessageViewListener() {
            @Override
            public void onBack() {
                setState(STATE_NORMAL);
            }

            public void onNewMessage() {
                if (currentState != STATE_PRIVATE_MESSAGE) {
                    iv_message_flag.setVisibility(View.VISIBLE);
                }
            }
        });
        giftSendView = (GiftSendView) findViewById(R.id.giftSendView);
        giftSendView.setGiftSendViewListener(new GiftSendView.GiftSendViewListener() {
            @Override
            public void onSendGift(GiftForLive giftForLive) {
                sendGift(giftForLive);
            }
        });

        gamePopupwind = (GamePopupwind) findViewById(R.id.gamePopupwind);
        gamePopupwind.setOnHideListener(new GamePopupwind.OnHideListener() {
            @Override
            public void onHide() {
                setState(STATE_NORMAL);
            }
        });
        gamePopupwind.init(1);

        gameListView = (GameListView) findViewById(R.id.gameListView);
        gameListView.setOnStartGameListener(new GameListView.StartGameListener() {
            @Override
            public void onStartGame() {
                setState(STATE_NIUNIU);
            }
        });

        beautySettingView = (BeautySettingView) findViewById(R.id.beautySettingView);
        beautySettingView.setListener(new BeautySettingView.OnBeautySettingChangeListener() {
            @Override
            public void onBlurSizeChange(int progress) {
                if (mLSMediaCapture != null) {
                    mLSMediaCapture.setFilterStrength(progress);
                }
            }
        });

        listView_message = (ListView) findViewById(R.id.listview_message);
        messageAdapter = new RoomMessageAdapter(this, roomMessageList);
        messageAdapter.setOnNameClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                RoomMessage message = roomMessageList.get(p);
                RoomManageDialog dialog = new RoomManageDialog(AnchorActivity.this);
                dialog.setIsAnchor(true);
                dialog.setData(room_id, message);
                dialog.show();
            }
        });
        listView_message.setAdapter(messageAdapter);

        atmosphere_view = (AtmosphereView) findViewById(R.id.atmosphere_view);
    }

    RequestCallback callback = new RequestCallback<EnterChatRoomResultData>() {
        @Override
        public void onSuccess(EnterChatRoomResultData param) {
            Log.e(TAG, "进入聊天室成功");
            NIMClient.getService(ChatRoomServiceObserver.class)
                    .observeReceiveMessage(incomingChatRoomMsg, true);
            tvTitleView.updateRoomMembers(room_id);
            startAddRobotTast();
        }

        @Override
        public void onFailed(int code) {
            Log.e(TAG, "进入聊天室失败:" + code);
            BaseApplication.getApp().reEnterRoom(callback, data);
        }

        @Override
        public void onException(Throwable exception) {
            Log.e(TAG, "进入聊天室出错");
        }
    };

    public void onEvent(DealEvent event) {
        sendDealMessage(chatRoomMessageParser.TYPE_GAME_DEAL);
    }

    public void onEvent(WinEvent event) {
        String msg = "在牛牛游戏中赢了" + event.getWin() + "钻石";
        sendRoomMessage(msg, ChatRoomMessageParser.TYPE_ROOM_MESSAGE);
    }

    private void initIM() {
        data = new EnterChatRoomData(room_id + "");
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (personalInfo != null && relationInfo != null) {
            data.setNick(personalInfo.getName());
            data.setAvatar(personalInfo.getAvatar());
            HashMap<String, Object> map = new HashMap<>();
            map.put("net_ease_id", UserConfig.getInstance().getNet_ease());
            map.put("user_id", personalInfo.getId() + "");
            map.put("icon", personalInfo.getAvatar());
            int level = relationInfo.getLevel();
            map.put("level", level);
            map.put("nick", personalInfo.getName());
            data.setExtension(map);
            data.setNotifyExtension(map);
        }
        NIMClient.getService(ChatRoomService.class).enterChatRoom(data)
                .setCallback(callback);

        //初始化消息解析器
        chatRoomMessageParser = new ChatRoomMessageParser(new ChatRoomMessageParser.ChatRoomMessageParseListener() {
            @Override
            public void onGift(Gift gift) {
                if (gift.is_dynamic) {
                    giftGifShowView.addGif(gift);
                    final RoomMessage roomMessage = new RoomMessage();
                    roomMessage.setType(1);
                    roomMessage.setName(gift.name);
                    roomMessage.setAvatar(gift.icon);
                    roomMessage.setUser_id(gift.user_id);
                    roomMessage.setNet_ease_id(gift.net_ease_id);
                    roomMessage.setLevel(gift.level);
                    roomMessage.setContent("送了一个" + gift.gift_name);
                    roomMessageList.add(roomMessage);
                    messageAdapter.notifyDataSetChanged();
                    listView_message.setSelection(listView_message.getBottom());
                } else {
                    giftShowView.addGift(gift);
                }
                author_income += gift.gift_scale * gift.gift_price * gift.gift_count * 10 / 100;
                tvTitleView.setCoins(author_income);
            }

            @Override
            public void onMessage(RoomMessage roomMessage) {
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onEnterMessage(RoomMessage roomMessage, boolean isTargetMe) {
                if (!isTargetMe) {
                    roomMessageList.add(roomMessage);
                    messageAdapter.notifyDataSetChanged();
                    listView_message.setSelection(listView_message.getBottom());
                    tvTitleView.addMember(room_id, roomMessage.getOperatorNeteaseId());
                }
            }

            @Override
            public void onExitMessage(RoomMessage roomMessage) {
                tvTitleView.removeMember(roomMessage.getOperatorNeteaseId());
            }

            @Override
            public void onDanmuMessage(RoomDanmuMessage roomDanmuMessage) {
                danmuShowView.addRoomDanmuMessage(roomDanmuMessage);
            }

            @Override
            public void onFinishLive() {

            }

            @Override
            public void onSetManager(RoomMessage roomMessage, boolean isManager, boolean isTargetMe) {
                if (roomManageListPopwindow != null) {
                    if (isManager) {
                        roomManageListPopwindow.addManager(roomMessage.getTargetNeteaseId());
                        roomManageListPopwindow.removeMute(roomMessage.getTargetNeteaseId());
                    } else {
                        roomManageListPopwindow.removeManager(roomMessage.getTargetNeteaseId());
                    }
                }
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onSetMute(RoomMessage roomMessage, boolean isMute, boolean isTargetMe) {
                if (roomManageListPopwindow != null) {
                    if (isMute) {
                        roomManageListPopwindow.addMute(roomMessage.getTargetNeteaseId());
                        roomManageListPopwindow.removeManager(roomMessage.getTargetNeteaseId());
                    } else {
                        roomManageListPopwindow.removeMute(roomMessage.getTargetNeteaseId());
                    }
                }
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onLightOn(RoomMessage roomMessage) {
                atmosphere_view.addOne();
                roomMessageList.add(roomMessage);
                messageAdapter.notifyDataSetChanged();
                listView_message.setSelection(listView_message.getBottom());
            }

            @Override
            public void onGameDeal() {
            }

            @Override
            public void onGameBet() {
                updateYazhu();
            }

        });
    }

    private void updateYazhu() {
        request(new GointoGameParams(UserConfig.getInstance().getPersonalInfo().getId()), DealResponse.class, new Response.Listener<DealResponse>() {
            @Override
            public void onResponse(DealResponse baseResponse) {

                if (baseResponse.getStatusCode() == 6) {
                    gamePopupwind.setYazhu(baseResponse.getBets());
                }
            }
        });
    }

    private Observer<List<ChatRoomMessage>> incomingChatRoomMsg = new Observer<List<ChatRoomMessage>>() {
        @Override
        public void onEvent(List<ChatRoomMessage> messages) {
            for (ChatRoomMessage message : messages) {
                chatRoomMessageParser.parse(message);
            }
        }
    };

    private void getGiftlistData() {
        BaseBodyParams b = new BaseBodyParams();
        b.setUrl(Constant.UrlParams.LIVEGIFTS);
        request(b, LiveGiftResponse.class, new Response.Listener<LiveGiftResponse>() {
            @Override
            public void onResponse(LiveGiftResponse liveGiftResponse) {
                if (liveGiftResponse != null) {
                    giftSendView.setData(liveGiftResponse.getHash());
                }
            }
        });
    }

    private void getCoinsData() {
        BaseBodyParams b = new BaseBodyParams();
        b.setUrl(Constant.UrlParams.MY_COINS);
        request(b, CoinsResponse.class, new Response.Listener<CoinsResponse>() {
            @Override
            public void onResponse(CoinsResponse coinsResponse) {
                if (coinsResponse != null) {
                    myCoins = coinsResponse.getCarrots();
                    giftSendView.setCoins(myCoins);
                    gamePopupwind.setCoins(myCoins);
                }
            }
        });
    }

    private Random random = new Random();

    private void startAddRobotTast() {
        if (mHandler != null) {
            mHandler.postDelayed(postAddRobotTask, random.nextInt(2 * 60 * 1000) + 60 * 1000);
        }
    }

    private void stopAddRobotTast() {
        if (mHandler != null) {
            mHandler.removeCallbacks(postAddRobotTask);
        }
    }

    private Runnable postAddRobotTask = new Runnable() {
        @Override
        public void run() {
            if (tvTitleView.getMemberCount() < 10) {
                postAddRobot();
            }
            startAddRobotTast();
        }
    };

    private void postAddRobot() {
        //机器人接口
        request(new GetrobotsParam(room_id), BaseResponse.class, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse baseResponse) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        if (view == btn_chat) {
            setState(STATE_INPUT_MESSAGE);
        } else if (view == btn_message) {
            setState(STATE_PRIVATE_MESSAGE);
        } else if (view == btn_gift) {
//            setState(STATE_SELECT_GIFT);
            showFilterChooseDialog();
        } else if (view == btn_share) {
            if (shareDialog == null) {
                shareDialog = new ShareDialog(this,
                        UserConfig.getInstance().getPersonalInfo().getName() + "正在直播，快来支持一下吧！",
                        room_des,
                        UserConfig.getInstance().getPersonalInfo().getAvatar(),
                        "http://www.meiyuzhibo.cn/m/live.html?u=" + createRooomResponse.getUnique_id() + "&s=" + createRooomResponse.getHookup_screening_id());
            }
            shareDialog.show();
        } else if (view == btn_game) {
            setState(STATE_GAME);
        } else if (view == btn_switch_camera) {
            switchCamera();
        }
    }

    private void setState(int state) {
        switch (state) {
            case STATE_NORMAL:
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.VISIBLE);
                beautySettingView.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                break;
            case STATE_INPUT_MESSAGE:
                giftShowView.setVisibility(View.GONE);
                danmuShowView.setVisibility(View.VISIBLE);
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                privateMessageView.setVisibility(View.GONE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                inputView.setVisibility(View.VISIBLE);
                showSoftInputFromWindow(inputView.getEditView());
                beautySettingView.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                break;
            case STATE_PRIVATE_MESSAGE:
                iv_message_flag.setVisibility(View.GONE);
                giftShowView.setVisibility(View.GONE);
                danmuShowView.setVisibility(View.GONE);
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                privateMessageView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.GONE);
                layout_bottom_btn.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                beautySettingView.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                break;
            case STATE_SELECT_GIFT:
                giftSendView.setVisibility(View.VISIBLE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                gameListView.setVisibility(View.GONE);
                danmuShowView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                beautySettingView.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                break;
            case STATE_BEAUTY_SETTING:
                beautySettingView.setVisibility(View.VISIBLE);
                gamePopupwind.setVisibility(View.GONE);
                giftSendView.setVisibility(View.GONE);
                gameListView.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                break;
            case STATE_GAME:
                gameListView.setVisibility(View.VISIBLE);
                giftSendView.setVisibility(View.GONE);
                gamePopupwind.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                break;
            case STATE_NIUNIU:
                gamePopupwind.setVisibility(View.VISIBLE);
                gameListView.setVisibility(View.GONE);
                giftSendView.setVisibility(View.GONE);
                inputView.setVisibility(View.GONE);
                hideSoftInputFromWindow(inputView.getEditView());
                privateMessageView.setVisibility(View.GONE);
                giftShowView.setVisibility(View.VISIBLE);
                danmuShowView.setVisibility(View.VISIBLE);
                listView_message.setVisibility(View.VISIBLE);
                layout_bottom_btn.setVisibility(View.GONE);
                break;
        }
        toolsView.show(false);
        currentState = state;
    }

    private void sendGift(GiftForLive giftForLive) {
        // 发送礼物
        HashMap<String, Object> map = new HashMap<>();
        map.put("net_ease_id", UserConfig.getInstance().getNet_ease());
        map.put("user_id", UserConfig.getInstance().getLogingAccount());
        map.put("type", 2);
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            map.put("name", personalInfo.getName());
            map.put("icon", personalInfo.getAvatar());
        }
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (relationInfo != null) {
            map.put("level", relationInfo.getLevel());
        }
        map.put("gift_type", giftForLive.getId() + "");
        map.put("gift_name", giftForLive.getName());
        map.put("gift_icon", giftForLive.getImage_url());
        map.put("gift_count", giftForLive.gift_count);

        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(
                room_id + "", // 聊天室id
                "test message" + System.currentTimeMillis() // 文本内容
        );
        message.setRemoteExtension(map);
        // 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(ChatRoomService.class).sendMessage(message, false);
        chatRoomMessageParser.parse(message);
    }

    private void sendDanmuMessage(final String text) {
        int cost = Constant.Danmu_Price;
        if (myCoins < cost) {
            ToastUtil.show("您的钻石余额不足！");
            return;
        }
        myCoins -= cost;
        giftSendView.setCoins(myCoins);
        PostbarrageParams postbarrageParams = new PostbarrageParams(UserConfig.getInstance().getUserId(), 1);
        request(postbarrageParams, BaseResponse.class, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse onlyStatusResponse) {
                if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                    sendRoomMessage(text, ChatRoomMessageParser.TYPE_DANMU_MESSAGE);
                } else if (onlyStatusResponse.getStatusCode() == 2) {
                    ToastUtil.show("您的钻石余额不足！");
                } else {
                    ToastUtil.show("弹幕发送失败");
                }
            }
        });
    }

    private void sendRoomMessage(String text, int type) {
        // 创建文本/弹幕消息
        HashMap<String, Object> map = new HashMap<>();
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            map.put("name", personalInfo.getName());
            map.put("avatar", personalInfo.getAvatar());
        }
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (relationInfo != null) {
            map.put("level", relationInfo.getLevel());
        }
        map.put("net_ease_id", UserConfig.getInstance().getNet_ease());
        map.put("user_id", UserConfig.getInstance().getLogingAccount());
        map.put("type", type);
        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(
                room_id + "", // 聊天室id
                text // 文本内容
        );
        message.setRemoteExtension(map);
        // 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(ChatRoomService.class).sendMessage(message, false);
        chatRoomMessageParser.parse(message);
    }

    private void sendDealMessage(int type) {
        // 创建文本/弹幕消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", type);
        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(
                room_id + "", // 聊天室id
                System.currentTimeMillis() + "" // 文本内容
        );
        message.setRemoteExtension(map);
        // 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(ChatRoomService.class).sendMessage(message, false);
    }

    private void finishLive() {
        Intent intent = new Intent(this, AnchorFinishActivity.class);
        startActivityForResult(intent, REQUEST_FINISH);
    }

    public void onEvent(RechargeEvent event) {
        getCoinsData();
    }

    public void onEvent(YazhuEvent event) {
        sendDealMessage(chatRoomMessageParser.TYPE_GAME_BET);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_FINISH && resultCode == RESULT_OK) {

            stopCaptureTask();
            sendRoomMessage("", ChatRoomMessageParser.TYPE_FINISH_LIVE);

            BaseBodyParams b = new BaseBodyParams();
            b.setUrl(Constant.UrlParams.LIVECLOSE);
            request(b, BaseResponse.class, new Response.Listener<BaseResponse>() {
                @Override
                public void onResponse(BaseResponse onlyStatusResponse) {
                    ToastUtil.show("直播已关闭");
                    EventBus.getDefault().post(new NowLiveUpdateEvent());
                }
            });
            finish();
        }
    }

    //定时发送截图

    private Timer timer;
    private TimerTask timerTask;
    private static final long CAPTURE_TIME_INTERVAL = 1 * 60 * 1000;
    private Handler captureTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
//                    mLSMediaCapture.enableScreenShot();
                    postMembersNumberData();
                }
                break;
            }
        }
    };

    private void startCaptureTask() {
        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer(true);
        timerTask = new TimerTask() {
            public void run() {
                Message message = captureTaskHandler.obtainMessage(1);
                captureTaskHandler.sendMessage(message);
            }
        };
        timer.schedule(timerTask, 5000, CAPTURE_TIME_INTERVAL);
    }

    private void stopCaptureTask() {
        captureTaskHandler.removeMessages(1);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void postCaptureData() {
        //文件上传
        //("video_pic"代表切片；"avatar"代表头像)
        String body = new FileReqPackage(new UploadFileParams("video_pic")).packetParam();
        new Thread(new UploadFile(Constant.URL + Constant.UrlParams.UPLOAD, mScreenShotFilePath + "/" + mScreenShotFileName, body, new UploadCallBack() {
            @Override
            public void response(final UploadResponse response) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (response == null || response.getHash() == null || TextUtils.isEmpty(response.getHash().getAvatar_url())) {
//                            ToastUtil.show("上传失败");
//                        } else {
//                            ToastUtil.show("上传成功");
//                        }
//                    }
//                });
            }
        })).start();
    }

    //定时发送人数，维持心跳
    private void postMembersNumberData() {
        request(new AddnumParams(tvTitleView.getMemberCount()), BaseResponse.class, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse onlyStatusResponse) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }

    private String[] filterNameArray = {
            "普通",
            "美颜"
    };

    private void showFilterChooseDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("滤镜选择");
        builder.setItems(filterNameArray,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, int item) {
                        switch (item) {
                            case 0:
                                switchFilterTo(new GPUImageFilter());
                                break;
                            case 1:
                                switchFilterTo(new GPUImageFaceFilter());
                                break;
                        }
                    }
                });
        builder.create().show();
    }


    private void switchFilterTo(final GPUImageFilter filter) {
        if (mLSMediaCapture != null) {
            mLSMediaCapture.setFilterType(filter);
        }
    }

}
